package com.xja.wechat.common;

import com.google.gson.JsonObject;
import com.xja.wechat.domain.model.WX_User;
import org.json.JSONObject;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * 常量类
 */
public class Constant {
    //测试环境APPID
    //public static final String APPID="wx6cba9315efa9a68f";
    //测试环境APPSECRET
    //public static final String APPSECRET="701388327f1646ec480e8e15df0f7fcf";
    //测试环境url
    //public static  final String URL="http://0lov29o.hn3.mofasuidao.cn";
    //正式环境APPID
    public static final String APPID = "wxc37f01894579f97b";
    //正式环境APPSECRET
    public static final String APPSECRET = "f3bffdf6eaa1786384593030dd5ea24c";
    //正式环境url
    public static final String URL = "http://www.scorpio-cc.com";


    //AcessToken
    public static String ACCESSTOKEN = null;
    //上一次获取accessToken的时间
    public static Long ACCESSTOKEN_TIME = 0l;
    //jsapi_ticket
    public static String JSAPITICKET = null;
    //上一次获取jsapi_ticket的时间
    public static Long JSAPITICKET_TIME = 0l;

    /**
     * 获取临时二维码
     *
     * @param scene_id
     * @return JSONObject 数据需要入库
     */
    public static JSONObject getQr(Integer scene_id) {
        String url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + getAccessToken();
        JSONObject jsonObject = null;
        try {
            String str = "{\"expire_seconds\": 2592000, \"action_name\": \"QR_STR_SCENE\", \"action_info\": {\"scene\": {\"scene_str\": " + scene_id + "}}}";
            jsonObject = HttpClientUtil.doPost(url, str);
            if (jsonObject.has("ticket")) {
                /**
                 *
                 */
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return jsonObject;
    }

    /**
     * 网页授权--用户手动同意授权接口
     *
     * @param redirectUri 回调url
     * @return
     */
    public static String snsapi_userinfo(String redirectUri) {
        //授权后重定向的回调链接地址， 请使用 urlEncode 对链接进行处理
        String encode = "";
        try {
            encode = URLEncoder.encode(redirectUri, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + APPID +
                "&redirect_uri=" + encode + "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
    }

    /**
     * 网页授权--静默授权
     *
     * @param redirectUri
     * @return
     */
    public static String snsapi_base(String redirectUri) {
        //授权后重定向的回调链接地址， 请使用 urlEncode 对链接进行处理
        String encode = "";
        try {
            encode = URLEncoder.encode(redirectUri, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + APPID + "&redirect_uri=" + encode + "&response_type=code&scope=snsapi_base&state=123#wechat_redirect";
    }

    public static JSONObject scopeOauth2(String code) {
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + APPID + "&secret=" + APPSECRET + "&code=" + code + "&grant_type=authorization_code";
        JSONObject jsonObject = null;
        try {
            jsonObject = HttpClientUtil.doGet(url);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return jsonObject;
    }

    //拉取用户信息(需scope为 snsapi_userinfo)
    public static WX_User getUserInfoBySnsapiUserInfo(String openid, String access_token) {
        //System.out.println(openid);
        String getUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token +
                "&openid=" + openid + "&lang=zh_CN";
        WX_User wx_user = null;
        try {
            JSONObject userInfo = HttpClientUtil.doGet(getUserInfoUrl);
            wx_user = JsonUtil.fromJson(userInfo.toString(), WX_User.class);
            System.out.println("snsapi_userinfo" + userInfo.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return wx_user;
    }

    public static Map<String, Object> jsConfig(String targetUrl) {
        String jsapi_ticket = getJsApiTicket();
        long timestamp = System.currentTimeMillis() / 1000;
        String noncestr = SHA1.getNoncestr();
        String str = "jsapi_ticket=" + jsapi_ticket +
                "&noncestr=" + noncestr +
                "&timestamp=" + timestamp +
                "&url=" + targetUrl;
        //得到的str进行SHA1加密--得到签名
        String signature = SHA1.encode(str);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("appId", Constant.APPID);
        resultMap.put("timestamp", timestamp);
        resultMap.put("nonceStr", noncestr);
        resultMap.put("signature", signature);
        return resultMap;
    }

    /**
     * 获取微信js的临时票据
     *
     * @return
     */
    public static synchronized String getJsApiTicket() {
        Long nowTime = System.currentTimeMillis() / 1000;
        if (JSAPITICKET == null || ((nowTime - JSAPITICKET_TIME) > 7000)) {
            String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + getAccessToken() + "&type=jsapi";
            try {
                JSONObject jsonObject = HttpClientUtil.doGet(url);
                if (jsonObject.has("ticket")) {
                    JSAPITICKET = (String) jsonObject.get("ticket");
                    JSAPITICKET_TIME = System.currentTimeMillis() / 1000;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return JSAPITICKET;
    }

    /**
     * 获取全局接口唯一调用凭据，ACCESSToken
     *
     * @return
     */
    //synchronized  ---同步---线程安全
    public static synchronized String getAccessToken() {
        //初始ACCTESSTOKEN  是null.如果过期
        //获取到当前系统时间秒
        Long nowTime = System.currentTimeMillis() / 1000;
        if (ACCESSTOKEN == null || ((nowTime - ACCESSTOKEN_TIME) > 7000)) {
            //获取ACCtessToken主体
            String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + APPID + "&secret=" + APPSECRET;
            try {
                JSONObject jsonObject = HttpClientUtil.doGet(url);
                if (jsonObject.has("access_token")) {
                    ACCESSTOKEN = (String) jsonObject.get("access_token");
                    ACCESSTOKEN_TIME = System.currentTimeMillis() / 1000;//秒级别
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return ACCESSTOKEN;
    }

    /**
     * 根据用户openid获取用户基本信息
     *
     * @param openid
     * @return
     */
    public static WX_User getUserInfo(String openid) {

        String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + getAccessToken() + "&openid=" + openid + "&lang=zh_CN";
        WX_User wx_user = null;
        try {
            JSONObject jsonObject = HttpClientUtil.doGet(url);
            wx_user = JsonUtil.fromJson(jsonObject.toString(), WX_User.class);

        } catch (IOException e) {
            e.printStackTrace();
        }
        return wx_user;
    }

    public static void main(String[] args) {
        getJsApiTicket();
    }
}
